package com.rong.mbt.personal.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.ActivityManager;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.bean.BaseBean;
import com.rong.mbt.personal.bean.PersonalDetailInfoBean;
import com.rong.mbt.personal.bean.PersonalInfoBean;
import com.rong.mbt.personal.dialog.CustomerServiceDialog;
import com.rong.mbt.personal.utils.DlgUtil;
import com.rong.mbt.personal.utils.FileStorage;
import com.rong.mbt.personal.utils.ImageUtil;
import com.rong.mbt.personal.utils.PhoneUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class PersonalInfoActivity extends PBaseActivity {
    ImageView ivHeadProtrait;
    private PersonalInfoBean infoBean;
    private ImageView ivBack;
    private ImageView ivCs;
    private ImageView ivHeadProtrait1;
    private TextView tvName;
    private TextView registerPhone;
    private String mbtToken;
    private TextView tvDetailInfo;
    private PersonalDetailInfoBean.DataBean data;
    private TextView tvPassword;

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    public void initView() {
        super.initView();
        mPermissionsChecker = new PermissionsChecker(this);

        ivHeadProtrait = findViewById(R.id.act_personal_info_iv_head);
        ivBack = findViewById(R.id.head_blue_iv_left);
        ivCs = findViewById(R.id.head_blue_iv_right);
        ivHeadProtrait1 = findViewById(R.id.act_personal_info_iv_head);
        tvName = findViewById(R.id.p_info_name);
        registerPhone = findViewById(R.id.p_info_regisetphone);
        tvDetailInfo = findViewById(R.id.act_pi_tv_detail_info);
        tvPassword = findViewById(R.id.act_pi_password);
        getExtra();
        initNet();
        listener();
        if (infoBean != null) {
            initText();
        }

    }

    private void initNet() {
        OkGo.<String>get("http://service.kantingyong.com/userInfo/get")
                .tag(this)
                .headers("mbtToken", mbtToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i("test", "onSuccess  get  " + response.body());
//                        {"msg":"请求成功","resultCode":0}

                        PersonalDetailInfoBean bean = JSON.parseObject(response.body(), PersonalDetailInfoBean.class);
                        if (bean.getData() != null) {
//                            tvDetailInfo.setText("已完善");
                            tvDetailInfo.setText("");
                            data = bean.getData();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.i("test", "onError  " + response.body());
                    }
                });
    }

    private void initText() {
        if (infoBean == null || infoBean.getData() == null) {
            return;
        }

        if (infoBean.getData().getHeadimage() != null) {
            ImageUtil.loadCircleImage(PersonalInfoActivity.this,
                    infoBean.getData().getHeadimage(), ivHeadProtrait);
        }
        if (infoBean.getData().getName() != null) {
            tvName.setText(infoBean.getData().getName());
        }
        if (infoBean.getData().getPhone() != null) {
            registerPhone.setText(PhoneUtil.phoneShowStar(infoBean.getData().getPhone()));
        }

    }

    private void listener() {
        ivHeadProtrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                photoDialog();
            }
        });
        ivCs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomerServiceDialog csDialog = new CustomerServiceDialog(PersonalInfoActivity.this);
                csDialog.show();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //安全设置
        tvPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, SecuritySettingActivity.class);
                intent.putExtra("mbtToken", mbtToken);
                intent.putExtra("phone", infoBean.getData().getPhone());
                startActivity(intent);
            }
        });

        //登录日志
        findViewById(R.id.act_pi_loginlog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, LoginLogActivity.class);
                intent.putExtra("mbtToken", mbtToken);
                intent.putExtra("phone", infoBean.getData().getPhone());
                startActivity(intent);
            }
        });
        //退出登录
        findViewById(R.id.act_pi_bt_unlogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkGo.<String>get("http://service.kantingyong.com/user/logout")
                        .tag(this)
                        .headers("mbtToken", mbtToken)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                BaseBean baseBean = JSON.parseObject(response.body(), BaseBean.class);
                                if (baseBean.isSuccess()) {
                                    SharedPreferences config = getSharedPreferences("config", Context.MODE_PRIVATE);
                                    config.edit().putInt("getAllUserInfoState", 0).commit();
//                                    ARouter.getInstance().build("/personal/TradingPwdSettingActivity").navigation();
                                    ARouter.getInstance().build("/acitvity/login").navigation();
                                    ActivityManager.exit();
                                } else {
                                    Toast.makeText(PersonalInfoActivity.this, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        });
        //我的二维码
        findViewById(R.id.p_info_line_qrcode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, MyQRcodeActivity.class);
                intent.putExtra("infoBean", infoBean);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);
            }
        });
        //个性签名
        findViewById(R.id.p_info_line_sign).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalInfoActivity.this, IndividualitySignActivity.class);
                intent.putExtra("mbtToken", mbtToken);
                startActivity(intent);
            }
        });
    }
    //修改昵称
    public void clickName(View view) {
        Intent intent = new Intent(PersonalInfoActivity.this, UpdateNameActivity.class);
        intent.putExtra("mbtToken", mbtToken);
        startActivity(intent);
    }
    //手机号码
    public void registerPhone(View view) {
        Intent intent = new Intent(PersonalInfoActivity.this, BindingPhoneActivity.class);
        intent.putExtra("phone", infoBean.getData().getPhone());
        intent.putExtra("mbtToken", mbtToken);
        startActivity(intent);
    }
    //详细资料
    public void detilInfo(View view) {
        Intent intent = new Intent(PersonalInfoActivity.this, PersonalDetailInfoActivity.class);
        intent.putExtra("mbtToken", mbtToken);
        if (data != null) {
            intent.putExtra("data", data);
        }
        startActivity(intent);
    }

    public void getExtra() {
        infoBean = (PersonalInfoBean) getIntent().getSerializableExtra("infoBean");
        mbtToken = getIntent().getStringExtra("mbtToken");
    }

    //上传头像 和更新头像
    public void updateHeadProtrait(final File file) {

        OkGo.<String>post("http://service.kantingyong.com/user/editUserHeadImg")
                .tag(this)
                .isMultipart(true)
                .headers("mbtToken", mbtToken)
                .params("file", file)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ImageUtil.loadCircleImage(PersonalInfoActivity.this,
                                file, ivHeadProtrait);
                        ImageDlg.cancel();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

    }

    private static final int REQUEST_PICK_IMAGE = 1; //相册选取
    private static final int REQUEST_CAPTURE = 2;  //拍照
    private static final int REQUEST_PICTURE_CUT = 3;  //剪裁图片
    private static final int REQUEST_PERMISSION = 4;  //权限请求
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private Uri imageUri;//原图保存地址
    private boolean isClickCamera;
    private String imagePath;
    ProgressDialog ImageDlg;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_PICK_IMAGE://从相册选择
                if (data != null) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            case REQUEST_CAPTURE://拍照
                if (resultCode == RESULT_OK) {
                    cropPhoto();
                }
                break;
            case REQUEST_PICTURE_CUT://裁剪完成
                File file = getFile();
                File picFile;
                if (isClickCamera) {
                    picFile = file;
                } else {
                    picFile = new File(imagePath);
                }
                Luban.with(this).load(picFile)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                ImageDlg = DlgUtil.showProgressDlg(PersonalInfoActivity.this, "正在加载中...");
                            }

                            @Override
                            public void onSuccess(File file) {
                                updateHeadProtrait(file);
                                ImageDlg.cancel();
                            }

                            @Override
                            public void onError(Throwable e) {
                                ImageDlg.cancel();
                            }
                        }).launch();
                break;
            case REQUEST_PERMISSION://权限请求
                if (resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
                    finish();
                } else {
                    if (isClickCamera) {
                        openCamera();
                    } else {
                        selectFromAlbum();
                    }
                }
                break;
        }
    }

    private Dialog dialog_photo;

    @SuppressLint("NewApi")
    private void photoDialog() {
        dialog_photo = new Dialog(this, R.style.photo_dialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_take_photo, null);
        dialog_photo.setContentView(view);
        Window window = dialog_photo.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.bottomDialogStyle);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        if (!dialog_photo.isShowing()) {
            dialog_photo.show();
        }
        view.findViewById(R.id.tv_open_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        openCamera();
                    }
                } else {
                    openCamera();
                }
                isClickCamera = true;
            }
        });
        view.findViewById(R.id.tv_choose_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        selectFromAlbum();
                    }
                } else {
                    selectFromAlbum();
                }
                isClickCamera = false;
            }
        });
    }

    /**
     * 打开系统相机
     */
    private void openCamera() {
        File file = new FileStorage().createIconFile();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(PersonalInfoActivity.this, "com.rong.mbt.personal.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_PERMISSION,
                PERMISSIONS);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            imagePath = imageUri.getPath();
        }
        cropPhoto();
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 裁剪
     */
    private void cropPhoto() {
        File file = new FileStorage().createCropFile();
        Uri outputUri = Uri.fromFile(file);//缩略图保存地址
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUEST_PICTURE_CUT);
    }

    private static String path = "/sdcard/myHead/";//sd路径

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void handleImageBeforeKitKat(Intent intent) {
        imageUri = intent.getData();
        imagePath = getImagePath(imageUri, null);
        cropPhoto();
    }

    @NonNull
    private File getFile() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File file = new File(FileStorage.getLocalDir("picture"), System.currentTimeMillis() + ".jpg");
        try {
            InputStream is = getContentResolver().openInputStream(imageUri);
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bis = new BufferedInputStream(is);
            int len;
            byte[] buffer = new byte[2048];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return file;
    }
}
